package com.koro.tool;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ExcelUtils<T> {


    /**
     * 实体对象
     */
    public Class<T> clazz;

    public ExcelUtils(Class<T> clazz) {
        this.clazz = clazz;
    }


   /* public void readExcel(HttpServletResponse response, List<T> list, String sheetName) {
        FileInputStream fileInputStream = new FileInputStream(filePath + "poiexcel07.xlsx");

        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        //获取第一行
        Row row1 = sheet.getRow(0);
        //获取第一行的第一个单元格
        Cell cell11 = row1.getCell(0);
        //获取第一行第二个单元格
        Cell cell12 = row1.getCell(1);
        System.out.println("第一行第一个单元格的内容是："+cell11.getStringCellValue());
        System.out.println("第一行第二个单元格的内容是："+cell12.getStringCellValue());

        //获取第一行
        Row row2 = sheet.getRow(1);
        //获取第一行的第一个单元格
        Cell cell21 = row2.getCell(0);
        //获取第一行第二个单元格
        Cell cell22 = row2.getCell(1);
        System.out.println("第一行第一个单元格的内容是："+cell21.getStringCellValue());
        System.out.println("第一行第二个单元格的内容是："+cell22.getStringCellValue());
    }*/


    public void writeExcel(List<T> list, String workName,HttpServletResponse response) throws IOException {
       /* Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        for (int i = 0 ; i < list.size() ; i++) {
            Row row = sheet.createRow(i + 1);
            Field[] fields = clazz.getDeclaredFields();

            for(int j = 0 ; j < fields.length ; j++) {
                fields[j].setAccessible(true);
                if(i == 0) {
                    Cell cell = row.createCell(j + 1);
                    cell.setCellValue(fields[j].getName());
                } else {
                    try {
                        Object o = fields[j].get(list.get(i));
                        Cell cell = row.createCell(j + 1);
                        cell.setCellValue(String.valueOf(o));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }*/

        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("大文件导出优化测试");

        long begin = System.currentTimeMillis();

        for (int rowNum = 0; rowNum <65536 ; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for (int cellNum = 0; cellNum < 10 ; cellNum++) {
                Cell cell = row.createCell(cellNum);
                cell.setCellValue("("+(rowNum+1) + "," + (cellNum+1)+")");
            }

        }


        /*List<List<T>> lists = splitList(list);
        Workbook workbook = new SXSSFWorkbook();
        for(int i = 0 ; i < lists.size() ; i++) {
            Sheet sheet = workbook.createSheet("sheet_" + i);
            for (int j = 0; j < lists.get(i).size() ; j++) {
                Row row = sheet.createRow(j+1);
                Field[] fields = clazz.getDeclaredFields();
                if(j == 0) { // 表头填充
                    for (int m = 0 ; m < fields.length ; m++) {
                        Cell cell = row.createCell(m+1);
                        cell.setCellValue(fields[m].getName());
                    }
                }
            }
        }*/

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("大文件导出优化测试" + ".xls", "UTF-8"));

        FileOutputStream fileOutputStream = new FileOutputStream(workName + ".xls");
        workbook.write(fileOutputStream);
        // 清理临时文件
        ((SXSSFWorkbook) workbook).dispose();
        fileOutputStream.close();
        workbook.close();


     //   FileUtils.writeBytes(filePath, response.getOutputStream());

    }

    public List<List<T>> splitList(List<T> list) {

        // 按每5个一组分割
        int partialLimit = 20000;
        // 获取需要分割的次数，注意不能直接除以批次数量,会丢失数据;
        int limit = (list.size()+partialLimit -1)/partialLimit;
        // 获取分割后的集合
        List<List<T>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel()
                .map(a -> list.stream().skip((long) a * partialLimit).limit(partialLimit).parallel()
                        .collect(Collectors.toList())).collect(Collectors.toList());
        return splitList;
    }


    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7,8,9,10);
        ExcelUtils excelUtils = new ExcelUtils(Integer.class);
        List<List<Integer>> lists = excelUtils.splitList(list);
        // 执行具体业务方法。打印代替
        System.out.println(lists);
    }
}
